package com.li.temperature.chart.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.li.temperature.chart.R;
import com.li.temperature.chart.impl.IPhoneStatusObserver;
import com.li.temperature.chart.service.PhoneStatusManager;
import com.li.temperature.chart.service.PhoneStatusService;
import com.li.temperature.chart.util.ConfigA;
import com.li.temperature.chart.util.CustomToast;
import com.li.temperature.chart.util.ShareUtil;
import com.li.temperature.chart.util.WeakHandler;

public class MainActivity extends Activity implements OnClickListener, IPhoneStatusObserver, OnItemSelectedListener {

    public static final String TAG = "suhuazhi";
    public static final int MSG_UPDATE_UI = 0;
    public static final int MSG_UPDATE_STATUS = 1;
    public static final int MSG_UPDATE_FIST_DATA = 2;
    public static final int MSG_UPDATE_SECOND_DATA = 3;
    public static final int MSG_UPDATE_X_DATA = 4;

    private static final int REQUEST_CODE = 0x66;

    private Button btn_start;
    private Button btn_float;
    private Spinner sp_step;
    private TextView tv_XData;
    private TextView tv_fistData;
    private TextView tv_secondData;

    private List<Integer> mDataSpeedList;
    private ArrayAdapter<Integer> mDataSpeedAdapter;
    private PhoneStatusManager mPhoneStatusManager;

    private Handler mHandler = new PhoneDataHandler(this);

    private static class PhoneDataHandler extends WeakHandler<MainActivity> {
        public PhoneDataHandler(MainActivity owner) {
            super(owner);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = getOwner();
            if (activity == null) {
                return;
            }

            switch (msg.what) {
            case MSG_UPDATE_UI:
                activity.tv_fistData.setText((String) msg.obj);
                break;
            case MSG_UPDATE_STATUS:
                int status = (Integer) msg.obj;
                switch (status) {
                case PhoneStatusService.STATUS_RUNNING:
                    activity.btn_start.setText(R.string.btn_stop_title);
                    activity.sp_step.setEnabled(false);
                    break;
                case PhoneStatusService.STATUS_STOP:
                    activity.sp_step.setEnabled(true);
                    activity.btn_start.setText(R.string.btn_start_title);
                    activity.tv_fistData.setText("");
                    activity.tv_secondData.setText("");
                    activity.tv_XData.setText("");
                    break;
                default:
                    break;
                }
                break;
            case MSG_UPDATE_FIST_DATA:
                activity.tv_fistData.setText((String) msg.obj);
                break;
            case MSG_UPDATE_SECOND_DATA:
                activity.tv_secondData.setText((String) msg.obj);
                break;
            case MSG_UPDATE_X_DATA:
                activity.tv_XData.setText((String) msg.obj);
                break;
            default:
                break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initValue();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (PhoneStatusService.isRunning) {
            btn_start.setText(R.string.btn_stop_title);
        } else {
            btn_start.setText(R.string.btn_start_title);
        }

        sp_step.setSelection(mDataSpeedList.indexOf(getPredictionStep()), true);
    }

    private void initView() {
        sp_step = (Spinner) findViewById(R.id.sp_step);
        btn_start = (Button) findViewById(R.id.btn_start);
        btn_float = (Button) findViewById(R.id.btn_float);
        tv_XData = (TextView) findViewById(R.id.tv_XData);
        tv_fistData = (TextView) findViewById(R.id.tv_fistData);
        tv_secondData = (TextView) findViewById(R.id.tv_secondData);
    }

    private void initValue() {
        mPhoneStatusManager = PhoneStatusManager.getInstance(this);

        mDataSpeedList = getDataSpeedList();
        mDataSpeedAdapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_list_item_1, mDataSpeedList);
        sp_step.setAdapter(mDataSpeedAdapter);
    }

    private void initListener() {
        btn_start.setOnClickListener(this);
        btn_float.setOnClickListener(this);
        mPhoneStatusManager.setIPhoneStatusObserver(this);
        sp_step.setOnItemSelectedListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.btn_start:
            if (btn_start.getText().equals(getString(R.string.btn_start_title))) {
                startMonitor();
            } else {
                stopMonitor();
            }
            break;
        case R.id.btn_float:
            requestAlertWindowPermission();
            break;

        default:
            break;
        }

    }

    private void requestAlertWindowPermission() {
        try {
            Intent intent = new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION");
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, REQUEST_CODE);
            CustomToast.showToast(this, getString(R.string.toast_float_tip), Toast.LENGTH_LONG);
        } catch (Exception e) {
            CustomToast.showToast(getApplicationContext(), R.string.tip_float_error_toast, Toast.LENGTH_LONG);
        }

    }

    private void startMonitor() {
        Intent intent = new Intent(this, PhoneStatusService.class);
        intent.setAction(PhoneStatusService.ACTION_START_MONITOR);
        startService(intent);
    }

    private void stopMonitor() {
        Intent intent = new Intent(this, PhoneStatusService.class);
        intent.setAction(PhoneStatusService.ACTION_STOP_MONITOR);
        startService(intent);
    }

    @Override
    public void updateStatus(int value) {
        Message msg = new Message();
        msg.what = MSG_UPDATE_STATUS;
        msg.obj = value;
        mHandler.sendMessage(msg);
    }

    @Override
    public void updateFistData(String result) {
        Message msg = new Message();
        msg.what = MSG_UPDATE_FIST_DATA;
        msg.obj = result;
        mHandler.sendMessage(msg);
    }

    @Override
    public void updateSecondData(String result) {
        Message msg = new Message();
        msg.what = MSG_UPDATE_SECOND_DATA;
        msg.obj = result;
        mHandler.sendMessage(msg);
    }

    @Override
    public void updateXData(String result) {
        Message msg = new Message();
        msg.what = MSG_UPDATE_X_DATA;
        msg.obj = result;
        mHandler.sendMessage(msg);
    }

    private List<Integer> getDataSpeedList() {
        ArrayList<Integer> result = new ArrayList<Integer>();
        result.add(ConfigA.A_F_10s);
        result.add(ConfigA.A_F_15s);
        result.add(ConfigA.A_F_20s);
        return result;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        int value = (Integer) parent.getItemAtPosition(position);
        setPredictionStep(value);
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {

    }

    private void setPredictionStep(int value) {
        ShareUtil mShareUtil = new ShareUtil(this);
        mShareUtil.setShare(ConfigA.KEY_PREDICT_STEP, value);
    }

    private int getPredictionStep() {
        return new ShareUtil(this).getInt(ConfigA.KEY_PREDICT_STEP, ConfigA.A_F_20s);
    }
}
